package FromDB;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.PieDataset;
import org.jfree.data.jdbc.JDBCPieDataset;

import DB.DBConnecter;

public class FromOracle {

	public static void main(String[] args) {
		FromOracle d = new FromOracle();
		JFreeChart dbdata = d.createNumberEmpsPerDeptPieChart();
		d.writePngBasedOnChart(dbdata,"d:/dbdata.png",500,500);
	}

	/**
	 * Create pie chart representing percentage of employees in each department
	 * that has at least one employee.
	 * 
	 * @return Pie chart; null if no image created.
	 */
	public JFreeChart createNumberEmpsPerDeptPieChart() {
		JFreeChart pieChart = null;

		final String QUERY_NUMBER_EMPLOYEES_PER_DEPARTMENT = "SELECT S_DEPT.NAME, count(*) AS num_employees "
				+ "FROM S_DEPT, S_EMP "
				+ "WHERE S_EMP.DEPT_ID = S_DEPT.ID "
				+ "GROUP BY S_DEPT.NAME";

		final String TITLE_EMPS_PER_DEPT = "Employees Per Department";

		try {
			PieDataset pieDataset = new JDBCPieDataset(
					DBConnecter.getConnection(),
					QUERY_NUMBER_EMPLOYEES_PER_DEPARTMENT);

			pieChart = ChartFactory.createPieChart(TITLE_EMPS_PER_DEPT, // chart
																		// title
					pieDataset, true, // legend displayed
					true, // tooltips displayed
					false); // no URLs

		} catch (SQLException sqlEx) // checked exception
		{
			System.err.println("Error trying to acquire JDBCPieDataset.");
			System.err.println("Error Code:" + sqlEx.getErrorCode());
			System.err.println("SQLSTATE:" + sqlEx.getSQLState());
			sqlEx.printStackTrace();
		}

		return pieChart;
	}

	/**
	 * Write .png file based on provided JFreeChart.
	 * 
	 * @param aChart
	 *            JFreeChart.
	 * @param aFileName
	 *            Name of file to which JFreeChart will be written..
	 * @param aWidth
	 *            Width of image.
	 * @param aHeight
	 *            Height of image.
	 */
	public static void writePngBasedOnChart(JFreeChart aChart, String aFileName,
			int aWidth, int aHeight) {
		try {
			ChartUtilities.writeChartAsPNG(new FileOutputStream(aFileName),
					aChart, aWidth, aHeight);
		} catch (IOException ioEx) {
			System.err.println("Error writing PNG file " + aFileName);
		}
	}
}
